package com.jing.ads.net;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.jing.ads.application.MD5;
import com.jing.ads.net.ADSHttpManager.Request;

public class ADSImgDownloader {

	private static ADSImgDownloader downloader;

	private static final String ROOT_DIR = "JingADS";
	private static final String IMG_DIR = "icon";

	private File imgFile;

	private ArrayList<String> imgList = new ArrayList<String>();

	private ADSHttpManager manager;

	public interface ImgCallBack {
		public void callback(Bitmap bitmap);
	}
	
	private ADSImgDownloader(Context context) {
		manager = ADSHttpManager.getInstance(context);
		File rDir = new File("/sdcard/" + ROOT_DIR);
		if (!rDir.exists()) {
			rDir.mkdirs();
		}
		imgFile = new File(rDir, IMG_DIR);
		if (!imgFile.exists()) {
			imgFile.mkdirs();
		}
	}

	public static ADSImgDownloader getInstance(Context context) {
		if (downloader == null) {
			downloader = new ADSImgDownloader(context);
		}
		return downloader;
	}

	public void onDownload(final String url, final ImgCallBack callback) {
		if (TextUtils.isEmpty(url)) {
			return;
		}
		if (imgList.contains(url)) {
			return;
		}
		imgList.add(url);
		if (inCache(url)) {
			ImgTask t = new ImgTask(url, null, callback);
			t.execute("");
			return;
		}
		Request r = new Request();
		r.isImg = true;
		r.isGet = true;
		r.url = url;
		r.callBack = new RequestCallBack() {

			@Override
			public void onFetch(boolean success, Object data) {
				if (success) {
					ImgTask t = new ImgTask(url, (byte[]) data, callback);
					t.execute("");
				}
			}
		};
		manager.onRequest(r);
	}

	private boolean inCache(final String url) {
		String n = MD5.MD5Encode(url);
		try {
			File i = new File(imgFile, n);
			return i.exists();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	class ImgTask extends AsyncTask<String, Void, Bitmap> {

		private String url;
		private byte[] data;
		private ImgCallBack callback;
		
		public ImgTask (String url, byte[] data, ImgCallBack callback) {
			this.data = data;
			this.url = url;
			this.callback = callback;
		}
		
		@Override
		protected Bitmap doInBackground(String... params) {
			try {
				File f = new File(imgFile, MD5.MD5Encode(url));
				if (!f.exists()) {
					f.createNewFile();
					FileOutputStream fos = new FileOutputStream(f);
					fos.write(data);
					fos.close();
				}
				Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
				return bitmap;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap bitmap) {
			imgList.remove(url);
			callback.callback(bitmap);
		}
	}
}
